package com.douyang.util;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.douyang.base.enumeration.OrderStatementStatusEnum;
import com.douyang.model.OrderStatement;
import com.douyang.service.OrderStatementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
public class AlipayUtil {
    // "<-- 请填写您的应用私钥，例如：MIIEvQIBADANB ... ... -->";
    @Value("${alipay.privateKay}")
    String privateKey;
    //"<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->"
    @Value("${alipay.alipayPublicKey}")
    String alipayPublicKey;
    @Value("${alipay.appId}")
    String appId;

    @Value("${alipay.quitUrl}")
    String quitUrl;
    @Value("${alipay.returnUrl}")
    String returnUrl;
    @Value("${alipay.notifyUrl}")
    String notifyUrl;

    @Value("${alipay.serverUrl}")
    String serverUrl;

    @Autowired
    @Lazy
    private OrderStatementService orderStatementService;

    public  AlipayConfig getAlipayConfig() {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(serverUrl);
        alipayConfig.setAppId(appId);
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

    //创建订单
    public String  sendToAlipay(String tradeNo,String totalAmount,String subject) throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        // 设置商户订单号
        model.setOutTradeNo(tradeNo);
        // 设置订单总金额
        model.setTotalAmount(totalAmount);
        // 设置订单标题
        model.setSubject(subject);

        // 设置产品码(有问题就把我去掉)
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        // 设置PC扫码支付的方式
        model.setQrPayMode("1");
        //支付成功后点击完成会自动跳转回商家页面地址， 同时在 URL 地址上附带支付结果参数
        request.setReturnUrl(returnUrl);
        //异步通知地址，用于接收支付宝推送给商户的支付/退款成功的消息。
        request.setNotifyUrl(notifyUrl);
        request.setBizModel(model);

        // 如果需要返回GET请求，请使用
        // AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
        String form = alipayClient.pageExecute(request, "POST").getBody();
        System.out.println(form);
        return form;
    }

    //手动获取交易结果
    public void getPayResult(String outTradeNo) throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();

        // 设置订单支付时传入的商户订单号
        model.setOutTradeNo(outTradeNo);

//        // 设置支付宝交易号
//        model.setTradeNo("2014112611001004680 073956707");

        // 设置查询选项
        List<String> queryOptions = new ArrayList<String>();
        queryOptions.add("trade_settle_info");
        model.setQueryOptions(queryOptions);

        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
    }

    //退款
    public Double alipayTradeRefund(String orderStatementID,String refundReason,String price) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setOutTradeNo(orderStatementID);
        model.setRefundReason(refundReason);
        model.setRefundAmount(price);
        request.setBizModel(model);
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println(response.getBody());
            return new JSONObject(response.getBody())
                    .getJSONObject("alipay_trade_refund_response")
                    .get("refund_fee",Double.class);
        }else{
            return null;
        }

    }

    public Boolean check(Map<String, String> params) throws AlipayApiException {
        //签验
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8","RSA2");
        log.info("-------------------异步请求已接受，验签完成，结果为{}--------",signVerified);
        return signVerified;
    }
}
